package com.teama4.shop.controller;

import com.teama4.shop.domain.Store;
import com.teama4.shop.service.StoreService;
import com.teama4.shop.utils.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/Store")
public class StoreController {
    @Autowired
    private StoreService storeService;

    int tag;

    @GetMapping("/findStore")
    public String findStore(@RequestParam("id") int id, @RequestParam("tag") int tag, Model model) {
        Store store = storeService.selectByPrimaryKey(id);
        this.tag = tag;
        model.addAttribute("store", store);
        model.addAttribute("title", "修改店铺");
        return "/admin/store-add";
    }

    @GetMapping("/goToAddPage")
    public String goToAddPage(Model model){
        Store store = new Store();
        store.setBusinessLicense("blank.png");
        model.addAttribute("store", store);
        model.addAttribute("title", "增加店铺");
        return "/admin/store-add";
    }

    @PostMapping("/addStore")
    public String addStore(Store store, MultipartFile file) throws IOException {
        if(!file.isEmpty()) {
            String filePath = "/myFile/img/businessLicensePic";
            String filename = file.getOriginalFilename();
            String sname = filename.substring(filename.lastIndexOf("."));
            String name = UUID.randomUUID() + sname;
            store.setBusinessLicense(name);
            FileUtil.dictionary_add(file, filePath, name);
            storeService.saveStore(store);
        }
        if(tag != 0) {
            return "redirect:/index/merchantStoreList?id=" + tag;
        } else {
            return "redirect:/index/storeList";
        }
    }

    @DeleteMapping("/deleteStore")
    @ResponseBody
    public Boolean deleteStore(@RequestParam("id") int id) {
        int deleted = storeService.deleteByPrimaryKey(id);
        return deleted > 0;
    }

    @GetMapping("/showMessageContent")
    public String showMessageContent(int id, Model model) {
        Store store = storeService.selectByPrimaryKey(id);
        model.addAttribute("store", store);
        return "/admin/admin-message-show";
    }

    @GetMapping("/approve")
    public String approve(int id) {
        Store store = storeService.selectByPrimaryKey(id);
        storeService.updateByPrimaryKeySelective(store);
        return "redirect:/index/messageList";
    }

    @GetMapping("/reject")
    public String reject(int id) {
        storeService.deleteByPrimaryKey(id);
        return "redirect:/index/messageList";
    }
}
